import React, { Component, Suspense } from "react";
import { connect } from "dva";
import router from "umi/router";
import { List, Button, Icon, Card, Avatar, Form, Input, message, Select, Spin, Table, Modal, TreeSelect } from "antd";

const { Option } = Select;
const { confirm } = Modal;

import { delFile, enabledFile, getRepostFile, getCancelPostFile, getFileCategoryTree, docMoveCategory, docBatchAsync } from '@/services/knowledgeFile';
import styles from "./index.less";
import Ellipsis from "@/components/Ellipsis";
import UserSession from "@/UserSession";
import { routerRedux } from "dva/router";
import UploadFile from "../editFile/uploadFile";
import moment from "moment";
import pptImg from '@/assets/ppt.png';
import pdfImg from '@/assets/pdf.png';
import txtImg from '@/assets/txt.png';
import fileImg from '@/assets/file.png';
import wrodImg from '@/assets/wrod.png';
import updateAsync from "@/assets/homeImgV2/updateAsync.png";

class FileList extends Component {
	constructor(props) {
		super(props);
		this.state = {
			page: 1,
			limit: 10,
			formInfo: null,
			selectedRowKeys: [],
			fileIdList: [],
			moveVisible: false,
			moveCategoryId: "",
			treeData: [],
			categoryLoading: false
		};
		this.columns = [
			{
				key: "docTitle",
				align: "left",
				title: "文档名称",
				dataIndex: "docTitle",
				width: 200,
				render: (text, item) => {
					return (
						<span style={{ cursor: "pointer" }} onClick={() => this.addOrEdit(item.id, item)}>{text}</span>
					)
				}
			},
			{
				key: "docType",
				align: "left",
				title: "文档类型",
				dataIndex: "docType",
				width: 120,
				render: text => {
					let label = '';
					switch (text) {
						case '0':
							label = 'WORD';
							break;

						case '1':
							label = '';
							break;

						case '2':
							label = 'PPT';
							break;

						case '3':
							label = 'PDF';
							break;

						case '4':
							label = 'TXT';
							break;

						case '5':
							label = '自建';
							break;

						default:
							label = '';
							break;
					};
					return label;
				}
			},
			{
				title: '创建时间',
				dataIndex: 'createTime',
				key: 'createTime',
				width: 150,
				render: (createTime) => {
					if (createTime) {
						return moment(createTime).format('YYYY-MM-DD')
					} else {
						return createTime;
					}
				}
			},
			{
				title: "操作",
				align: "left",
				width: 400,
				render: (text, item) => {
					return (
						<span style={{ display: 'flex', alignItems: 'center', gap: '16px', color: '#3E5BFF' }}>
							<span onClick={() => this.addOrEdit(item.id, item)}>预览</span>
							<span onClick={() => this.delFile(item.id)}>删除</span>
							<span onClick={() => this.addOrEdit(item.id, item)}>下载</span>
						</span>
					);
				},
			},
		];
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		};
	}

	fetchQaListBySearch = e => {
		e.preventDefault();
		this.setState({ page: 1 }, () => this.getFileInfoList())
	}

	getFileInfoList = () => {
		const { page, limit } = this.state;
		this.props.form.validateFields((err, values) => {
			if (!err) {
				this.setState({ formInfo: values }, () => {
					this.props.fetchGraphListByPage(page, limit, values)
				})
			}
		});
	}

	// 新增自定义文档
	addKnowledgeFile = (id) => {
		// const { pathId, dispatch, fileCategoryId, fileCategoryPath } = this.props;
		// let pathname = "";
		// if (UserSession.isSystemKnowledge()) {
		// 	pathname = "/systemKnowledge/" + pathId + "/file/add";
		// } else {
		// 	pathname = "/myKnowledge/" + pathId + "/file/add";
		// };
		// let query = id ? { fileCategoryId, fileCategoryPath, id } : { fileCategoryId, fileCategoryPath };
		// dispatch(routerRedux.push({ pathname, query }));
	}

	// 批量文档上传
	updateFile = () => {
		this.uploadFileRef.showModal('BATCH');
	}

	// 预览or查看
	addOrEdit = (fileId, item) => {
		// if (item.docType == 5) {
		// 	this.addKnowledgeFile(fileId);
		// 	return;
		// };
		// const { pathId, dispatch, fileCategoryId } = this.props;
		// let pathname = "";
		// if (UserSession.isSystemKnowledge()) {
		// 	pathname = "/systemKnowledge/" + pathId + "/file/preview";
		// } else {
		// 	pathname = "/myKnowledge/" + pathId + "/file/preview";
		// };

		// dispatch(routerRedux.push({
		// 	pathname,
		// 	query: { fileCategoryId, fileId, fileName: item.docName, fileUrl: item.docPath, previewPath: item.previewPath },
		// }));
	}

	// 删除
	delFile = id => {
		const { formInfo } = this.state;
		const that = this;

		confirm({
			title: "删除文档知识点",
			content: "是否确定删除此文档知识点？",
			okText: "确认",
			cancelText: "取消",
			onOk: async () => {
				let res = await delFile({ id });
				// console.log(res);
				if (res.code == 0) {
					message.info(res.msg);
					that.props.fetchGraphListByPage(1, 10, formInfo);
				}
			},
			onCancel() { },
		});
	}

	fenye = (page) => {
		const { formInfo } = this.state;
		this.setState({ page }, () => {
			this.props.fetchGraphListByPage(page, 10, formInfo);
		})
	}

	render() {
		const { getFieldDecorator } = this.props.form;
		const { selectedRowKeys, moveVisible, treeData, categoryLoading, moveCategoryId } = this.state;
		const { list, total, graphLoading, current, fileCategoryId, fileCategoryPath, fileCategoryParentId, authority } = this.props;
		const rowSelection = {
			selectedRowKeys,
			onChange: (selectedRowKeys) => {
				this.setState({ selectedRowKeys, fileIdList: selectedRowKeys });
			},
		};
		let getImg = (key) => {
			let imgHtml = '';
			switch (key) {
				case '0':
					imgHtml = <img src={wrodImg} style={{ width: '24px' }} />;
					break;

				case '1':
					imgHtml = <img src={fileImg} style={{ width: '20px' }} />;
					break;

				case '2':
					imgHtml = <img src={pptImg} style={{ width: '24px' }} />;
					break;

				case '3':
					imgHtml = <img src={pdfImg} style={{ width: '24px' }} />;
					break;

				case '4':
					imgHtml = <img src={txtImg} style={{ width: '24px' }} />;
					break;

				case '5':
					imgHtml = <img src={fileImg} style={{ width: '20px' }} />;
					break;

				default:
					imgHtml = <img src={fileImg} style={{ width: '20px' }} />;
					break;
			};
			return imgHtml;
		}

		return (
			<Spin spinning={graphLoading}>
				<div className={styles.cardList}>
					<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
						<Form layout='inline' onSubmit={this.fetchQaListBySearch}>
							<Form.Item>
								{getFieldDecorator("key")(
									<Input placeholder='请输入关键字' style={{ width: 250 }} allowClear />
								)}
							</Form.Item>
							<Form.Item style={{ margin: 0 }}>
								<Button type='primary' htmlType='submit'>查询</Button>
							</Form.Item>
						</Form>
						<div style={{ margin: '14px 0 16px' }}>
							<Button type="primary" style={{ marginRight: 16 }} onClick={() => this.addKnowledgeFile()}>新增文档知识</Button>
							<Button onClick={() => this.updateFile()} style={{ marginRight: 16 }}>批量上传</Button>
						</div>
					</div>
					<Table
						rowSelection={rowSelection}
						dataSource={list}
						columns={this.columns}
						rowKey="id"
						pagination={{
							onChange: (page) => this.fenye(page),
							current: current,
							pageSize: 10,
							total: parseInt(total),
							showQuickJumper: true,
						}}
						scroll={{ x: "auto", y: 555 }}
					/>
					<UploadFile
						onRef={ref => this.uploadFileRef = ref}
						fileCategoryId={fileCategoryId}
						fileCategoryPath={fileCategoryPath}
						getFileList={this.fenye}
						rootCategoryId={this.props.pathId}
					/>
				</div>
			</Spin>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(FileList));
